/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
export default class Svgmethods {
  clickOpen (call, call2) {
    const file = document.getElementById('importimg').files[0]
    const filetype = file.type
    const reader = new FileReader()
    const reader2 = new FileReader()
    const filesize = file.size
    if (filetype !== 'image/svg+xml' && filetype !== 'image/png' && filetype !== 'image/jpeg') {
      call('error', 'type')
      return
    }
    if (filesize > 1024 * 1024 * 10) { // 10M换算字节
      call('error', 'size')
      return
    }
    if (filetype === 'image/svg+xml') {
      reader2.readAsDataURL(file)
      reader2.addEventListener('load', async (readerEvent) => {
        const imageSrc = readerEvent.target.result
        // 调用计算图片大小的方法
        calculateImageSize(imageSrc).then(function ({width, height}) {
          // 通过ES6的结构赋值来得到图片的宽和高
          let svgsize = {
            width,
            height
          }
          call2('vectorgraph', svgsize)
          reader.readAsText(file, 'UTF-8')
          reader.addEventListener('load', async (readerEvent) => {
            const content = readerEvent.target.result
            call('vectorgraph', content)
          })
        })
      })
    }
    if (filetype === 'image/png' || filetype === 'image/jpeg') {
      reader.readAsDataURL(file)
      reader.addEventListener('load', async (readerEvent) => {
        // 图片的 base64 格式, 可以直接当成 img 的 src 属性值
        const imageSrc = readerEvent.target.result
        // 调用计算图片大小的方法
        calculateImageSize(imageSrc).then(function ({width, height}) {
          // 通过ES6的结构赋值来得到图片的宽和高
          let pngsize = {
            width,
            height
          }
          call2('picture', pngsize)
          const _base64 = reader.result
          const content = _base64
          call('picture', content)
        })
      })
    }
  }
}

// 根据图片地址获取图片的宽和高
const calculateImageSize = function (url) {
  return new Promise(function (resolve, reject) {
    const image = document.createElement('img')
    image.addEventListener('load', function (e) {
      resolve({
        width: e.target.width,
        height: e.target.height
      })
    })

    image.addEventListener('error', function () {
      console.log('error')
    })

    // 将图片的url地址添加到图片地址中
    image.src = url
  })
}
